/* Datetime utility functions */
DateTime = {
	diff:function(date1, date2, unit){ // what is date2 relative to date1
		var unit = unit || 's';
		var diff = date1.getTime() - date2.getTime();
		var diffSec = Math.round(-diff / (1000)); // round to the second;
		var result = diffSec;
		if(unit == 'm'){
			result = result / 60;
		} else if (unit == 'h'){
			result = result / (60 * 60);
		}
		return result;
	},
	compare:function(date1, date2, unit){
		return DateTime.diff(date1,date2,unit);
	},
	isSameDay:function(date1,date2){
		var fullDate1 = (date1.getMonth()+1) + '/' + date1.getDate() + '/' + date1.getFullYear();
		var fullDate2 = (date2.getMonth()+1) + '/' + date2.getDate() + '/' + date2.getFullYear();
		return fullDate1 == fullDate2;
	},
	toStruct:function(date){
		if(date===undefined){
			date = new Date();
		}
		var result = {};
		result.year = date.getFullYear();
		result.month = date.getMonth() + 1;
		result.date = date.getDate();
		result.hour = date.getHours();
		result.minute = date.getMinutes();
		result.second = date.getSeconds();
		return result;
	},
	increment:function(date,days){ // days = 1 or -1
		var struct = DateTime.toStruct(date);
		struct.date = struct.date+days;
		// increment the month
		var monthdaylimit = DateTime.getMonthDayLimit(struct.month,struct.year);
		// up
		if(struct.date > monthdaylimit){
			struct.month++;
			struct.date = 1;
		}
		if(struct.month == 13){
			struct.year++;
			struct.month = 1;
		}
		// down
		if(struct.date < 1){
			struct.month--;
		}
		if(struct.month == 0){
			struct.month = 12;
			struct.year--;
		}
		if(struct.date == 0){
			struct.date = DateTime.getMonthDayLimit(struct.month,struct.year);
		}
		var date = new Date(struct.month+'/'+struct.date+'/'+struct.year);
		return date;
	},
	add:function(date,days){
		if(days == 0){
			return date;
		}
		if(days > 0){
			for(var i = 0; i < days; i++){
				date = DateTime.increment(date,1);
			}
		} else {
			days = days * -1;
			for(var i = 0; i < days; i++){
				date = DateTime.increment(date,-1);
			}
		}
		return date;
	},
	getMonthDayLimit:function(month,year){
		var monthdaylimit = 31;
		if(month == '2'){
			monthdaylimit = 28;
			if(year % 4 == 0){
				monthdaylimit = 29;
			}
		} else if(month == 4 || month == 6 || month == 9 || month == 11){
			monthdaylimit = 30;
		}
		return monthdaylimit;
	},
	toString:function(date){
		var struct = DateTime.toStruct(date);
		for(var key in struct){
			if(struct[key] < 10){
				struct[key] = '0'+struct[key];
			}
		}
		var result = struct.month + '/' + struct.date + '/' + struct.year + ' ' + struct.hour + ':' + struct.minute + ':' + struct.second;
		return result;
	}
}